package com.fujimana.rockincat.restree.message;

import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

public class MessageManager {

	public static final MessageManager INSTANCE = new MessageManager();

	private MessageManager() {
	}

	public static final MessageManager getInstance() {
		return INSTANCE;
	}

	public MessageRepository createRepositpory(List<String> resources,
			List<Locale> locales) {

		Map<String, Message> messages = new ConcurrentHashMap<String, Message>();

		for (String res : resources) {
			for (Locale locale : locales) {
				loadMessage(res, locale, messages);
			}
		}

		MessageRepository repo = new MessageRepository(messages);
		return repo;
	}

	private void loadMessage(String res, Locale locale, Map<String, Message> map) {

		try {
			ResourceBundle rb = ResourceBundle.getBundle(res, locale);

			if (rb == null) {
				return;
			}

			Enumeration<String> keys = rb.getKeys();
			while (keys.hasMoreElements()) {
				String key = keys.nextElement();
				String value = rb.getString(key);

				Message m = map.get(key);
				if (m == null) {
					m = new Message(key);
					map.put(key, m);
				}

				m.setMesssage(value, locale);
			}

		} catch (MissingResourceException e) {
			// TODO
		}

	}

}
